<?php
class dl
{
    public static function bring($url, $cache_folder)
    {
        $pieces = explode('.', $url);
        $file_type = $pieces[count($pieces) - 1];

        if($file_type == 'jpg')
        {
            dl::bring_jpg($url, $cache_folder);
        }
        else if($file_type == 'torrent')
        {
            dl::bring_torrent($url);
        }
        else
        {
            dl::bring_jpg($url, $cache_folder);
        }
    }
    public static function bring_jpg($url, $cache_folder)
    {
        $imagename= util::get_filename_from_url($url);
        $localimage = $cache_folder.$imagename;
        header('Content-type: image/jpeg');
        header('Expires: Thu, 01 Dec 2020 16:00:00 GMT');
        if(file_exists($localimage))
        {
            echo readfile($localimage);
        }
        else
        {
            $content = util::read_url($url);
            file_put_contents($localimage, $content);
            echo $content;
        }

    }
    public static function bring_torrent($url)
    {
        $file_name = explode('/', $url);
        $file_name = $file_name[count($file_name) - 1];
        # header info for download
        //header('Content-Length: ' . filesize($url));
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Expires: 0');
        header('Content-Description: Torrent Download');
        header('Content-type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.$file_name);
        if(strpos($url,"torcache") !== FALSE)
        {
            header("X-Compression: gzip");
            header("Content-Encoding: gzip");
        }

        ob_clean();
        flush();

        //$content = file_get_contents($url);
        readfile($url);
        exit();

    }
}

?>